﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

using DevComponents.DotNetBar;
using TextEditor;
using System.Xml;
using DevComponents.AdvTree;
using Bifrost.WcfSvr;
using Bifrost;
using CLIENT_EMR.TEMPLATE;


namespace CLIENT_EMR.Doctor_Bll
{
    public partial class ucDocOperater : UserControl
    {
   
        private string Record_Time = null;
        private string Record_Content = null;

        public static string SelectTemplate; //当前选择的模版

        int wcfresalut = 0;
        bool wcfresaultflag = false;
        /// <summary>
        /// 授权操作权限
        /// </summary>
        public string OperateState;

        /// <summary>
        /// 当前文书ID
        /// </summary>
        public string KindText;

        private frmText CurrentFrmText;

        /// <summary>
        /// 弹出时间选择窗体的返回值，点击确定返回True，点击取消返回false
        /// </summary>
        public static bool isFlagtrue = false;

        public delegate void DeleGetRecord(string time, string content);
       
        public ucDocOperater()
        {
            InitializeComponent();
        }

        public ucDocOperater(InPatientInfo patinfo)
        {
            InitializeComponent();
            ComHelp.patientinfo = patinfo;
        }

        /// <summary>
        /// 获得文书记录时间，记录内容
        /// </summary>
        /// <param name="time">记录时间</param>
        /// <param name="content">记录内容</param>
        private void GetDate(string time, string content)
        {
            this.Record_Time = time;
            this.Record_Content = content;
        }

        private void tabControl1_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 刷新全部文书
        /// </summary>
        private void RefAllText()
        {
            #region 全部文书
            trvAllText.Nodes.Clear();
            UcTreeNode[] nodes = App.wc.ReflashBookTree(ComHelp.patientinfo).Childnodes;
            for (int i = 0; i < nodes.Length; i++)
            {
                Node tn = new Node();
                tn.Name = nodes[i].Name;
                tn.Text = nodes[i].Text;
                tn.Tag = nodes[i].Tag;
                if (nodes[i].Childnodes.Length > 0)
                {
                    getChildNodes(ref tn, nodes[i].Childnodes);
                }
                trvAllText.Nodes.Add(tn);
            }
            SetTreeNodesImage(trvAllText.Nodes);
            trvAllText.ExpandAll();
            trvAllText.AutoScrollOffset = new Point(0);
            #endregion
        }

        private void RefFinishText()
        {
            #region 已写文书
            trvFinishDoc.Nodes.Clear();
            UcTreeNode finishnode = App.wc.GetFinishNode(ComHelp.patientinfo.Id.ToString());
            Node finshtn = new Node();
            finshtn.Name = finishnode.Name;
            finshtn.Text = finishnode.Text;
            finshtn.Tag = finishnode.Tag;
            if (finishnode.Childnodes.Length > 0)
            {
                getChildNodes(ref finshtn, finishnode.Childnodes);
            }
            trvFinishDoc.Nodes.Add(finshtn);
            SetTreeNodesImage(trvFinishDoc.Nodes);
            trvFinishDoc.ExpandAll();
            trvAllText.AutoScrollOffset = new Point(0);
            #endregion
        }

        private void ucDocOperater_Load(object sender, EventArgs e)
        {
            RefFinishText();
            RefAllText();
            bar1.Text = "文书";
            dockContainerItem1.Text = "文书";
        }

        private void getChildNodes(ref Node tn, UcTreeNode[] cnodes)
        {
            for (int i = 0; i < cnodes.Length; i++)
            {
                Node ctn = new Node();
                ctn.Name = cnodes[i].Name;
                ctn.Text = cnodes[i].Text;
                ctn.Tag = cnodes[i].Tag;
                if (cnodes[i].ForeColor != null)
                {
                    ctn.Style = new ElementStyle();
                    ctn.Style.TextColor = ColorTranslator.FromHtml(cnodes[i].ForeColor);
                }
                if (cnodes[i].Childnodes.Length > 0)
                {
                    getChildNodes(ref ctn, cnodes[i].Childnodes);
                }             
                tn.Nodes.Add(ctn);
            }
        }

        /// <summary>
        /// 新建文书操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void trvAllText_DoubleClick(object sender, EventArgs e)
        {
            try
            { 
                //验证TabControl是否有重复           
                for (int i = 0; i < tctlDoc.Tabs.Count; i++)
                {
                    if (trvAllText.SelectedNode.Text == tctlDoc.Tabs[i].Text)
                    {
                        tctlDoc.SelectedTabIndex = i;
                        return;
                    }
                }
                if (trvAllText.SelectedNode.Nodes.Count == 0)
                {

                    int tid = 0;
                    if (trvAllText.SelectedNode.Tag.ToString().Contains("Class_Text"))
                    {
                        Class_Text text = trvAllText.SelectedNode.Tag as Class_Text;
                        //text.Ishighersign
                        ComHelp.patientinfo = App.wc.InitPatient(ComHelp.patientinfo.Id.ToString()); //最新病人情况
                        InPatientInfo inPatient = null;
                        inPatient = ComHelp.patientinfo;
                        if (inPatient.Gender_Code.Trim() == "女")
                        {
                            inPatient.Gender_Code = "1";
                        }

                        if (tctlDoc.Tabs.Count > 0)
                        {
                            /*
                             * IsSameTabItem()判断tctlDoc是否有相同的文书类型(TabItem)
                             * IsSameBookDoc()判断tctlDoc是否有相同的文书(TabItem)
                             */
                            string strdoctype = text.Textname.ToString();
                            if (IsSameTabItem(trvAllText.SelectedNode.Name, DateTime.Now.ToString("yyyy-MM-dd HH:mm")) == false)          //false表示里面没有相同的tabItem
                            {

                                //20160308 毛成文添加
                                //判断该文书是否锁定
                                if (strdoctype.Contains("日常病程记录"))
                                {
                                    strdoctype = "病程(二级)";
                                }
                                //袁杨添加 160315
                                if (strdoctype.Contains("上级查房记录"))
                                {
                                    strdoctype = "上级查房记录";
                                }
                                //创建非定制文书
                                CreateTabItem(tid);
                            }                           
                        }
                        else
                        {
                            //20160308 毛成文添加
                            //判断该文书是否锁定
                            string strdoctype = text.Textname.ToString();
                            if (strdoctype.Contains("日常病程记录"))
                            {
                                strdoctype = "病程(二级)";
                            }
                            //袁杨添加 160315
                            if (strdoctype.Contains("上级查房记录"))
                            {
                                strdoctype = "上级查房记录";
                            }                            
                            //创建非定制文书
                            CreateTabItem(tid);
                        }
                    }                 
                }
            }
            catch
            {
            }
        }

        /// <summary>
        /// 创建新的tabItem
        /// </summary>
        /// <param name="tid">文书id</param>
        private void CreateTabItem(int tid)
        {
            try
            {

                Record_Content = "";
                Record_Time = "";
                string docflaag = "";
                string suporSign = "";  //查房上级医师的userId
                /*
                 * 创建新的tabItem 的实现思路：
                 * 1.当前选中的文书类别，如果是单例文书，就查出其内容。
                 * 2.当前选中的是病人文书，根据文书id，查出其内容
                 */
                //CurrentNode = advAllDoc.SelectedNode.Clone() as TreeNode;
                // 获得当前时间，精确到分钟
                // string time = string.Format("{0:g}", App.GetSystemTime());
                DevComponents.DotNetBar.TabControlPanel tabctpnDoc = new DevComponents.DotNetBar.TabControlPanel();
                tabctpnDoc.AutoScroll = true;
                DevComponents.DotNetBar.TabItem page = new DevComponents.DotNetBar.TabItem();
                //tctlDoc.TabItemClose += new TabStrip.UserActionEventHandler(tctlDoc_TabItemClose);           
                page.Click += new EventHandler(page_Click);


                if (tid == 0)
                {
                    #region 新建文书
                    if (trvAllText.SelectedNode.Nodes.Count == 0)
                    {
                        //子节类型节点
                        Class_Text text = trvAllText.SelectedNode.Tag as Class_Text;
                        //新建文书，page页的Name用分号隔开，第一位：代表文书类型ID;第二位：文书类型;第三位：代表新建文书;第四位：是否单例文书
                        page.Name = trvAllText.SelectedNode.Name + ";" + trvAllText.SelectedNode.Tag.GetType().ToString() + ";0;" + text.Issimpleinstance;

                        //文书对应的医务处规则ID
                        DataSet YWC_RAW = App.wc.GetDataSet("select a.var_id from t_doc_quality_relation a  where a.text_id=" + text.Id + "");
                        if (YWC_RAW.Tables[0].Rows.Count > 0)
                        {
                            string strval = "";
                            for (int i = 0; i < YWC_RAW.Tables[0].Rows.Count; i++)
                            {
                                if (strval == "")
                                {
                                    strval = YWC_RAW.Tables[0].Rows[i][0].ToString();
                                }
                                else
                                {
                                    strval = strval + "," + YWC_RAW.Tables[0].Rows[i][0].ToString();
                                }
                            }
                        }

                        //if (App.UserAccount.CurrentSelectRole.Role_type != tempcl.Right_range &&
                        //    tempcl.Right_range != "A" &&
                        //   App.UserAccount.CurrentSelectRole.Role_type != "Z")//提供质控科查看痕迹,因为痕迹只在编辑状态才能查看
                        //{
                        //    page.Dispose();
                        //    tabctpnDoc.Dispose();
                        //    App.Msg("您没有书写该类文书的权限！");
                        //    return;
                        //}


                        page.Text = trvAllText.SelectedNode.Text + " " + " (" + ComHelp.patientinfo.Sick_Bed_Name + " 床)";

                        Class_Text select_text = trvAllText.SelectedNode.Tag as Class_Text;
                        page.Tag = ComHelp.patientinfo as object;
                        if (page.Tag != null)
                        {

                            string log_Tid = trvAllText.SelectedNode.Name;

                            //是否忽略空行
                            bool NeglectLine = IsNeglectLine(trvAllText.SelectedNode);

                            string textTitle = GetTextTitle(trvAllText.SelectedNode);

                            if (select_text.Other_textname != "")
                            {
                                textTitle = select_text.Other_textname;
                            }

                            InPatientInfo inpatient = page.Tag as InPatientInfo;
                           
                            Class_Text cText = trvAllText.SelectedNode.Tag as Class_Text;
                            //page.Tooltip = cText.Id.ToString();
                            if (cText.Submitted == "Y")
                            {
                                docflaag = "Y";

                            }
                            else
                            {
                                //App.SetToolButtonByUser("ttsbtnPrint", false);
                                docflaag = "N";
                            }
                            page.Tooltip = docflaag;

                            #region 时间标题设置
                            isFlagtrue = false;
                            if (select_text.Ishavetime == "A") //编辑器内显示时间标题
                            {
                                if (frmCreateDocSet.q_time == "")
                                {
                                    Record_Time = App.wc.GetSystemTime().ToString("yyyy-MM-dd HH:mm");
                                }
                                else
                                {
                                    DateTime temp = Convert.ToDateTime(frmCreateDocSet.q_time);
                                    Record_Time = temp.ToString("yyyy-MM-dd HH:mm");
                                }
                            }
                            else if (select_text.Ishavetime == "B" && tid == 0)//弹出提示框，编辑器内显示文书名+时间标题
                            {
                                if (frmCreateDocSet.q_time == "")
                                {
                                    Record_Time = App.wc.GetSystemTime().ToString("yyyy-MM-dd HH:mm");
                                }
                                else
                                {
                                    DateTime temp = Convert.ToDateTime(frmCreateDocSet.q_time);
                                    Record_Time = temp.ToString("yyyy-MM-dd HH:mm");
                                }
                                frmUpdateTime frmTime = null;
                                if (trvAllText.SelectedNode.Name == "127")//上级查房记录
                                {
                                    frmTime = new frmUpdateTime(Record_Time, "查房记录", true);
                                    frmTime.Event_GetRecord += new DeleGetRecord(GetDate);

                                    frmTime.ShowDialog();
                                    if (!isFlagtrue)
                                    {
                                        return;
                                    }
                                    suporSign = frmTime.suporSign;
                                }
                                else
                                {
                                    frmTime = new frmUpdateTime(Record_Time, trvAllText.SelectedNode.Text, false);
                                    frmTime.Event_GetRecord += new DeleGetRecord(GetDate);
                                    DialogResult dr = frmTime.ShowDialog();
                                    if (!isFlagtrue)
                                    {
                                        return;
                                    }
                                }
                            }
                            else if (select_text.Ishavetime == "")
                            {
                                if (Record_Time == "")
                                    Record_Time = App.wc.GetSystemTime().ToString("yyyy-MM-dd HH:mm");

                            }
                            if (trvAllText.SelectedNode.Text == "手术记录")
                            {
                                Record_Content = "手术记录";

                            }


                            #endregion
                            if (cText.Issimpleinstance == "1")            //1代表多实例文书
                            {
                                #region 多例文书
                                if (inpatient.Sick_Bed_Name != "")
                                {
                                    if (!IsSameBookDoc() && !IsSameTabItem(trvAllText.SelectedNode.Name, Record_Time))
                                    {
                                        if (page.Name.Split(';').Length == 4)
                                        {//多例文书选项添加时间记录,防止重复时间添加
                                            page.Name += ";" + Record_Time;
                                        }
                                        //文书内容互读
                                        //string content = App.wc.DocFromXmlBytText(NowTree.SelectedNode.Name, DataInit.GetDefaultTemp(NowTree.SelectedNode.Name), inpatient);

                                        //文书默认模版
                                        string content = App.wc.GetDefaultTemp(trvAllText.SelectedNode.Name);



                                        frmText uctext = new frmText(cText.Id, 0, 0, textTitle, tid, inpatient, true, true, Record_Time, Record_Content);



                                        uctext.MyDoc.EnableShowAll = true;
                                        //添加文书，Ishighersign是否需要上级医师审签
                                        uctext.MyDoc.TextSuperiorSignature = cText.Ishighersign;
                                        uctext.MyDoc.HaveTubebedSign = "N";  //管床医生是否审签
                                        uctext.MyDoc.HaveSuperiorSignature = "N";//是否已经有过上级医生签名

                                        ////袁杨 150825 文书授权
                                        //if (OperateState != null && OperateState.Contains("补录"))
                                        //{
                                        //    uctext.MyDoc.Section_name = App.UserAccount.CurrentSelectRole.Section_name;//当前登录科室
                                        //}


                                        uctext.MyDoc.IgnoreLine = NeglectLine;
                                        //uctext.MyDoc.OnBackTextId += new EventHandler<BackEvenHandle>(MyDoc_OnBackTextId); //浏览界面修改文书
                                        //袁杨添加 2015-7-14
                                        uctext.MyDoc.OnDrawPageHeader += ComHelp.EMRDoc_OnDrawPageHeader;
                                        //
                                        XmlDocument tempxmldoc = new XmlDocument();
                                        tempxmldoc.PreserveWhitespace = true;
                                        if (select_text.Ishavetime != "")
                                        {
                                            uctext.MyDoc.NeedTimeTitle = true;
                                        }

                                        if (select_text.Isneedsign == "Y")
                                        {
                                            uctext.MyDoc.AutoGraph = true;
                                        }
                                        if (content != null)         //获取文书的默认模板
                                        {
                                            if (content.Contains("emrtextdoc"))
                                            {
                                                tempxmldoc.LoadXml(content);
                                                XmlNode xmlNode = tempxmldoc.SelectSingleNode("emrtextdoc");//查找<body>
                                                foreach (XmlNode bodyNode in xmlNode.ChildNodes)
                                                {
                                                    if (bodyNode.Name == "body")
                                                    {
                                                        if (select_text.Ishavetime != "")
                                                        {
                                                            bodyNode.InnerXml = @"<div id='C8272494' marginLeft='10' candelete='1' timeTitle='Y' name='' title='" + Record_Time + "   " + Record_Content + "'><p operatercreater='0' /></div>" + bodyNode.InnerXml;
                                                        }
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                tempxmldoc.LoadXml("<emrtextdoc/>");
                                                uctext.MyDoc.ToXML(tempxmldoc.DocumentElement);
                                                XmlNode xmlNode = tempxmldoc.SelectSingleNode("emrtextdoc");//查找<body>
                                                foreach (XmlNode bodyNode in xmlNode.ChildNodes)
                                                {
                                                    if (bodyNode.Name == "body")
                                                    {
                                                        bodyNode.InnerXml = "";

                                                        if (select_text.Ishavetime != "")
                                                        {
                                                            bodyNode.InnerXml = @"<div id='C8272494' marginLeft='10' candelete='1' timeTitle='Y' name='' title='" + Record_Time + "   " + Record_Content + "'><p operatercreater='0' /></div>";
                                                        }
                                                        if (trvAllText.SelectedNode.Text.Contains("日常病程记录") ||
                                                            trvAllText.SelectedNode.Text.Contains("医患沟通记录"))
                                                        {
                                                            uctext.MyDoc.HidleNameTitle = false;
                                                        }
                                                        bodyNode.InnerXml += content;
                                                    }
                                                }
                                            }
                                        }

                                        App.wc.filterInfo(tempxmldoc.DocumentElement, inpatient, uctext.MyDoc.Us.TextKind_id, uctext.MyDoc.Us.Tid);
                                        uctext.MyDoc.FromXML(tempxmldoc.DocumentElement);
                                        //手术知情同意书行间距默认6
                                        if (cText.Id == 1601)
                                        {
                                            uctext.MyDoc.Info.LineSpacing = 6;
                                            uctext.MyDoc.Info.ParagraphSpacing = 6;
                                        }
                                        uctext.MyDoc.ContentChanged();
                                        tabctpnDoc.Controls.Add(uctext);
                                        uctext.Dock = DockStyle.Fill;
                                        uctext.MyDoc.HidleNameTitle = false;
                                    }
                                }
                                #endregion
                            }
                            else
                            {
                                #region 单例文书
                                //string content = App.wc.GetDefaultTemp(trvAllText.SelectedNode.Name);
                                string content = App.wc.DocFromXmlBytText(trvAllText.SelectedNode.Name, inpatient.Id.ToString());
                                //string content = DocFromXmlBytText(NowTree.SelectedNode.Name,DataInit.GetDefaultTemp(NowTree.SelectedNode.Name));
                                //content=DocFromXmlBytText(CurrentNode.Name, content);
                                if (content != null)         //获取文书的默认模板
                                {
                                    frmText uctext = new frmText(cText.Id, 0, 0, textTitle, tid, inpatient, true, false, Record_Time, Record_Content);
                                    //显示所有按钮 (文书对比)
                                    //if (App.UserAccount.CurrentSelectRole.Role_type == "D" ||
                                    // App.UserAccount.CurrentSelectRole.Role_type == "N")
                                    //    text.MyDoc.EnableShowAll = false;
                                    //else
                                    //SetTextButtonFase(text);
                                    uctext.MyDoc.EnableShowAll = true;
                                    //添加文书，Ishighersign是否需要上级医师审签
                                    uctext.MyDoc.TextSuperiorSignature = cText.Ishighersign;
                                    //患者授权(委托)书 1603 自动出院同意书 1585 不需要管床签字
                                    if (select_text.Ishavetime != "")
                                    {
                                        uctext.MyDoc.NeedTimeTitle = true;
                                    }
                                    if (select_text.Isneedsign == "Y")
                                    {
                                        uctext.MyDoc.AutoGraph = true;
                                    }
                                    if (cText.Id == 1603 || cText.Id == 1585)
                                    {
                                        uctext.MyDoc.HaveTubebedSign = "Y";
                                    }
                                    else
                                    {
                                        uctext.MyDoc.HaveTubebedSign = "N";//管床医生是否审签
                                    }
                                    uctext.MyDoc.HaveSuperiorSignature = "N";//是否已经有过上级医生签名
                                    //uctext.MyDoc.OnBackTextId += new EventHandler<BackEvenHandle>(MyDoc_OnBackTextId);
                                    //袁杨添加 2015-7-14
                                    uctext.MyDoc.OnDrawPageHeader += ComHelp.EMRDoc_OnDrawPageHeader;
                                    //
                                    ////袁杨 修改 150825 文书授权
                                    //if (OperateState != null && OperateState.Contains("补录"))
                                    //{
                                    //    uctext.MyDoc.Section_name = App.UserAccount.CurrentSelectRole.Section_name;//当前登录科室
                                    //}


                                    uctext.MyDoc.IgnoreLine = NeglectLine;
                                    XmlDocument tempxmldoc = new XmlDocument();
                                    tempxmldoc.PreserveWhitespace = true;
                                    if (content.Contains("emrtextdoc"))
                                    {
                                        tempxmldoc.LoadXml(content);
                                        XmlNode xmlNode = tempxmldoc.SelectSingleNode("emrtextdoc");//查找<body>
                                        foreach (XmlNode bodyNode in xmlNode.ChildNodes)
                                        {
                                            if (bodyNode.Name == "body")
                                            {
                                                if (select_text.Ishavetime != "")
                                                {
                                                    bodyNode.InnerXml = @"<div id='C8272494' marginLeft='10' candelete='1' timeTitle='Y' name='' title='" + Record_Time + "   " + Record_Content + "'><p operatercreater='0' /></div>" + bodyNode.InnerXml;
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        tempxmldoc.LoadXml("<emrtextdoc/>");
                                        uctext.MyDoc.ToXML(tempxmldoc.DocumentElement);
                                        //tempxmldoc.SelectSingleNode("emrtextdoc/body").InnerXml = "";
                                        XmlNode xmlNode = tempxmldoc.SelectSingleNode("emrtextdoc");//查找<body>
                                        foreach (XmlNode bodyNode in xmlNode.ChildNodes)
                                        {
                                            if (bodyNode.Name == "body")
                                            {
                                                bodyNode.InnerXml = "";
                                                if (select_text.Ishavetime != "")
                                                {
                                                    uctext.MyDoc.NeedTimeTitle = true;
                                                    bodyNode.InnerXml = @"<div id='C8272494' marginLeft='10' candelete='1' timeTitle='Y' name='' title='" + Record_Time + "   " + Record_Content + "'><p operatercreater='0' /></div>";
                                                }
                                                bodyNode.InnerXml += content;
                                            }
                                        }
                                    }
                                    App.wc.filterInfo(tempxmldoc.DocumentElement, ComHelp.patientinfo, uctext.MyDoc.Us.TextKind_id, uctext.MyDoc.Us.Tid);
                                    uctext.MyDoc.FromXML(tempxmldoc.DocumentElement);

                                    //患者授权（委托）书行间距4
                                    if (cText.Id == 1603)
                                    {
                                        uctext.MyDoc.Info.LineSpacing = 4;
                                        uctext.MyDoc.Info.ParagraphSpacing = 4;
                                    }
                                    uctext.MyDoc.ContentChanged();
                                    tabctpnDoc.Controls.Add(uctext);
                                    uctext.Dock = DockStyle.Fill;
                                }
                                else
                                {
                                    frmText uctext = new frmText(cText.Id, 0, 0, textTitle, tid, inpatient, true, false, Record_Time, Record_Content);
                                    //显示所有按钮 (文书对比)
                                    if (App.UserAccount.CurrentSelectRole.Role_type == "D" ||
                                     App.UserAccount.CurrentSelectRole.Role_type == "N")
                                        uctext.MyDoc.EnableShowAll = false;
                                    //else
                                    //SetTextButtonFase(text);
                                    uctext.MyDoc.EnableShowAll = true;
                                    //添加文书，Ishighersign是否需要上级医师审签
                                    uctext.MyDoc.TextSuperiorSignature = cText.Ishighersign;
                                    uctext.MyDoc.HaveTubebedSign = "N";  //管床医生是否审签
                                    uctext.MyDoc.HaveSuperiorSignature = "N";//是否已经有过上级医生签名
                                    //uctext.MyDoc.OnBackTextId += new EventHandler<BackEvenHandle>(MyDoc_OnBackTextId);
                                    //袁杨添加 2015-7-14
                                    uctext.MyDoc.OnDrawPageHeader += ComHelp.EMRDoc_OnDrawPageHeader;
                                    //
                                    ////袁杨 修改 150825 文书授权
                                    //if (OperateState != null && OperateState.Contains("补录"))
                                    //{
                                    //    uctext.MyDoc.Section_name = App.UserAccount.CurrentSelectRole.Section_name;//当前登录科室
                                    //}

                                    uctext.MyDoc.IgnoreLine = NeglectLine;
                                    //SetToolEvent(uctext);
                                    //App.A_RefleshTreeBook = null;
                                    //App.A_RefleshTreeBook += new EventHandler(ReflashTrvBookEvent);
                                    tabctpnDoc.Controls.Add(uctext);
                                    uctext.Dock = DockStyle.Fill;
                                    if (select_text.Ishavetime != "")
                                    {
                                        uctext.MyDoc.NeedTimeTitle = true;
                                    }

                                    if (select_text.Isneedsign == "Y")
                                    {
                                        uctext.MyDoc.AutoGraph = true;
                                    }
                                    if (select_text.Ishavetime != "")
                                    {
                                        uctext.MyDoc._InsertMoreDiv(Record_Time + "   " + Record_Content);
                                    }
                                    XmlDocument tempxmldoc = new XmlDocument();
                                    tempxmldoc = ComHelp.XmlDoc(tempxmldoc, inpatient, uctext);
                                    uctext.MyDoc.FromXML(tempxmldoc.DocumentElement);
                                    uctext.MyDoc.ContentChanged();
                                    tabctpnDoc.Controls.Add(uctext);
                                    uctext.Dock = DockStyle.Fill;
                                }

                                #endregion
                            }



                        }


                    }
                    #endregion
                }
                else
                {
                    //修改文书，page页的Name用分号隔开，第一位：文书ID；第二位：文书类型
                    page.Name = trvFinishDoc.SelectedNode.Name + ";" + trvFinishDoc.SelectedNode.Tag.GetType().ToString();
                    page.Text = trvFinishDoc.SelectedNode.Text + " " + " (" + ComHelp.patientinfo.Sick_Bed_Name + " 床)";
                    if (trvFinishDoc.SelectedNode.Tag.ToString().Contains("Class_Text"))
                    {
                        #region 读取单例文书
                        Class_Text select_text = trvFinishDoc.SelectedNode.Tag as Class_Text;
                        //是否忽略空行
                        bool NeglectLine = IsNeglectLine(trvFinishDoc.SelectedNode);
                        string tempid = App.wc.isExitRecord(tid, ComHelp.patientinfo.Id);

                        string textTitle = GetTextTitle(trvFinishDoc.SelectedNode);
                        string DocContent = App.wc.GetTextDocXmlById(tempid);

                        frmText uctext = new frmText(Convert.ToInt32(tempid), 0, 0, textTitle, tid, ComHelp.patientinfo, true, false, Record_Time, Record_Content);
                        //SetTextButtonFase(text);
                        uctext.MyDoc.EnableShowAll = true;
                        //text.MyDoc.OnBackTextId += new EventHandler<BackEvenHandle>(MyDoc_OnBackTextId);
                        //袁杨添加 2015-7-14
                        uctext.MyDoc.OnDrawPageHeader += ComHelp.EMRDoc_OnDrawPageHeader;

                        uctext.MyDoc.IgnoreLine = NeglectLine;
                        XmlDocument tmpxml = new System.Xml.XmlDocument();
                        tmpxml.PreserveWhitespace = true;

                        InPatient_Doc textdoc = App.wc.GetDocbyId(trvFinishDoc.SelectedNode.Name, ComHelp.patientinfo.Id.ToString(), "Class_Text");

                        string ishighersign = textdoc.Ishighersign;
                        string havedoctorsign = textdoc.Havedoctorsign;
                        string havehighersign = textdoc.Havehighersign;
                        docflaag = textdoc.Submitted;
                        uctext.MyDoc.Section_name = textdoc.Section_name;
                        //修改文书，Ishighersign是否需要上级医师审签
                        uctext.MyDoc.TextSuperiorSignature = ishighersign;
                        uctext.MyDoc.HaveTubebedSign = havedoctorsign;  //管床医生是否审签
                        uctext.MyDoc.HaveSuperiorSignature = havehighersign;//是否已经有过上级医生签名

                        if (select_text.Ishavetime != "")
                        {
                            uctext.MyDoc.NeedTimeTitle = true;
                        }

                        if (select_text.Isneedsign == "Y")
                        {
                            uctext.MyDoc.AutoGraph = true;
                        }

                        tmpxml.LoadXml(DocContent);
                        if (trvFinishDoc.SelectedNode.Text.Contains("日常病程记录"))
                        {
                            uctext.MyDoc.HidleNameTitle = false;
                        }
                        App.wc.filterInfo(tmpxml.DocumentElement, ComHelp.patientinfo, select_text.Id, Convert.ToInt32(tempid));
                        uctext.MyDoc.FromXML(tmpxml.DocumentElement);
                        uctext.MyDoc.ContentChanged();
                        tabctpnDoc.Controls.Add(uctext);
                        uctext.Dock = DockStyle.Fill;
                        #endregion

                    }
                    else if (trvFinishDoc.SelectedNode.Tag.ToString().Contains("Patient_Doc"))
                    {
                        #region 读取多例文书
                        Class_Text cText = trvFinishDoc.SelectedNode.Parent.Tag as Class_Text;
                        //barTemplate.AutoHide = true;
                        //设置文书标题
                        string textTitle = GetTextTitle(trvFinishDoc.SelectedNode);
                        //是否可以忽略空行
                        bool NeglectLine = IsNeglectLine(trvFinishDoc.SelectedNode);

                        page.Tag = ComHelp.patientinfo as object;
                        Record_Time = trvFinishDoc.SelectedNode.Text;
                        InPatientInfo inpatient = page.Tag as InPatientInfo;                                          
                        InPatient_Doc pdoc = trvFinishDoc.SelectedNode.Tag as InPatient_Doc;
                        tid = pdoc.Id;
                        frmText uctext = new frmText(cText.Id, 0, 0, textTitle, tid, inpatient, true, true, Record_Time, Record_Content);

                        //袁杨添加  多例已写文书，暂存之后再提交签名无法自动插入的问题（该文书类型已经设置自动签名）
                        if (cText.Isneedsign == "Y")
                        {
                            uctext.MyDoc.AutoGraph = true;
                        }

                        if (textTitle.Contains("电脑血糖监测记录单") || textTitle.Contains("产科(新生儿)护理记录单") ||
                            textTitle.Contains("新生儿经皮胆红素观察表") || textTitle.Contains("缩宫素滴注观察记录单") ||
                            textTitle.Contains("PICC护理记录单"))
                        {
                            int nodeIndex = trvFinishDoc.SelectedNode.Index;
                            uctext.MyDoc.PageStartIndex = nodeIndex;
                        }                        
                        uctext.MyDoc.EnableShowAll = true;                       
                        uctext.MyDoc.Section_name = pdoc.Section_name;//文书所属科室                                                                        

                        //修改文书，Ishighersign是否需要上级医师审签
                        uctext.MyDoc.TextSuperiorSignature = pdoc.Ishighersign;
                        uctext.MyDoc.HaveTubebedSign = pdoc.Havedoctorsign;  //管床医生是否审签
                        uctext.MyDoc.HaveSuperiorSignature = pdoc.Havehighersign;//是否已经有过上级医生签名
                        uctext.MyDoc.SuporSign = pdoc.Highersignuserid; //查房医生的userId                        
                        //袁杨添加 2015-7-14
                        uctext.MyDoc.OnDrawPageHeader += ComHelp.EMRDoc_OnDrawPageHeader;
                        //
                        uctext.MyDoc.IgnoreLine = NeglectLine;                        

                        System.Xml.XmlDocument tmpxml = new System.Xml.XmlDocument();
                        tmpxml.PreserveWhitespace = true;
                        string content = "";                       
                        content=App.wc.GetTextDocXmlById(trvFinishDoc.SelectedNode.Name);                     
                        tmpxml.LoadXml(content);
                        App.wc.filterInfo(tmpxml.DocumentElement, ComHelp.patientinfo, cText.Id, tid);
                        uctext.MyDoc.FromXML(tmpxml.DocumentElement);
                        uctext.MyDoc.ContentChanged();
                        uctext.Dock = DockStyle.Fill;
                        tabctpnDoc.Controls.Add(uctext);
                        
                        #endregion
                    }
                }


                int patient_Id = ComHelp.patientinfo.Id;            
                tabctpnDoc.TabItem = page;
                tabctpnDoc.Dock = DockStyle.Fill;
                page.AttachedControl = tabctpnDoc;
                this.tctlDoc.Controls.Add(tabctpnDoc);
                this.tctlDoc.Tabs.Add(page);
                this.tctlDoc.Refresh();
                this.tctlDoc.SelectedTab = page;
            }
            catch(Exception ex)
            {
                App.Msg("文书创建或读取失败，原因："+ex.Message);
            }


        }

        /// <summary>
        /// 设置文书标题
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        private string GetTextTitle(Node node)
        {
            string textTitle = "";
            try
            {
                if (node != null)
                {
                    textTitle = node.Text;
                }
                if (node.Parent != null)
                {
                    if (node.Parent.Parent != null)
                    {
                        if ((node.Parent.Name == "103") || node.Name == "103"  //住院病程记录文书id
                            || (node.Parent.Parent != null && node.Parent.Parent.Name == "103"))
                        {
                            if (node.Parent.Name == "134" || node.Name == "134" ||
                               node.Parent.Parent.Name == "134")  //术前小结
                            {
                                textTitle = "手术前小结";
                            }
                            //else if (node.Name == "125")
                            //{
                            //    textTitle = "病程记录";
                            //}
                            else
                            {
                                textTitle = "病程记录";
                            }
                        }
                        else
                        {
                            if (node.Tag.GetType().Name.Contains("Patient_Doc"))
                            {
                                textTitle = node.Parent.Text;
                            }
                            else
                            {
                                textTitle = node.Text;
                            }
                            //textTitle = node.Text;
                        }
                        return textTitle;
                    }
                    else
                    {
                        if (node.Parent.Name == "103" || (node.Name == "103" && node.Text == "住院病程记录"))
                        {
                            if (node.Parent.Name == "134" || node.Name == "134")//术前小结
                            {
                                textTitle = "手术前小结";
                            }
                            //else if (node.Name == "125")
                            //{
                            //    textTitle = "病程记录";
                            //}
                            else
                            {
                                textTitle = "病程记录";
                            }
                        }
                        else
                        {
                            if (node.Tag.GetType().Name.Contains("Patient_Doc"))
                            {
                                textTitle = node.Parent.Text;
                            }
                            else
                            {
                                textTitle = node.Text;
                            }
                        }
                        return textTitle;
                    }
                }
                else
                {
                    Class_Text text = node.Tag as Class_Text;
                    if (text != null)
                    {
                        if (text.Parentid.ToString() == "103" || text.Id.ToString() == "103")
                        {
                            if (text.Id.ToString() == "125" || text.Id.ToString() == "103")
                            {
                                textTitle = "病程记录";
                            }
                            else
                            {
                                textTitle = "病程记录";
                            }
                        }
                        else
                        {
                            textTitle = node.Text;
                        }
                        if (text.Issimpleinstance == "0")
                        {

                            if (node.Text.Contains("(缺管床医生签名)"))
                            {
                                textTitle = textTitle.Replace("(缺管床医生签名)", "");
                            }
                            else if (node.Text.Contains("(缺上级医师签名)"))
                            {
                                textTitle = textTitle.Replace("(缺上级医师签名)", "");
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
            return textTitle;
        }

        /// <summary>
        ///  判断文书下面是否有相同名称的文书。
        /// </summary>
        /// <returns></returns>
        private bool IsSameBookDoc()
        {
            bool flag = false;            
            if (ComHelp.patientinfo != null)
            {

                UcTreeNode node = App.wc.SelectDoc2(ComHelp.patientinfo.Id, trvAllText.SelectedNode.Name);
                //当前创建文书的名称
                string new_TextName = Record_Time + "   " + Record_Content;
                foreach (UcTreeNode childNode in node.Childnodes)
                {
                    InPatient_Doc pdoc = childNode.Tag as InPatient_Doc;
                    //已经存在该类文书的名称
                    string old_TextName = pdoc.Docname;
                    //if (new_TextName.Equals(old_TextName))
                    if (old_TextName.Contains(Record_Time))
                    {
                        flag = true;
                        App.Msg("已经存在相同的文书！");
                        break;
                    }
                }
            }
            return flag;
        }
       

        /// <summary>
        /// 是否可以忽略空行
        /// </summary>
        /// <param name="node">当前选中的节点</param>
        /// <returns>true忽略，false不忽略</returns>
        private bool IsNeglectLine(Node node)
        {
            bool NeglectLin = true;
            if (node != null)
            {
                if (node.Tag.ToString().Contains("Class_Text"))//文书节点
                {
                    Class_Text class_Text = node.Tag as Class_Text;
                    if (class_Text.Txxttype == "915")//知情同意书
                    {
                        NeglectLin = false;
                    }
                }
                else if (node.Tag.ToString().Contains("Patient_Doc"))//文书内容节点
                {
                    if (node.Parent != null)
                    {
                        Class_Text class_Text = node.Parent.Tag as Class_Text;
                        if (class_Text.Txxttype == "915")//知情同意书
                        {
                            NeglectLin = false;
                        }
                    }
                }
            }
            return NeglectLin;
        }

        /// <summary>
        /// 初始化文书编辑器的病人信息
        /// </summary>
        /// <param name="uctext"></param>
        /// <param name="info"></param>
        private void SetTextEditorInfo(ref frmText uctext,InPatientInfo info)
        {
            uctext.MyDoc.Us = new UserInfo();

            uctext.MyDoc.Us.TextKind_id = Convert.ToInt32(trvAllText.SelectedNode.Name);
            uctext.MyDoc.Us.TextName = trvAllText.SelectedNode.Text;
            uctext.MyDoc.Us.InpatientInfo = info;   
                        
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void page_Click(object sender, EventArgs e)
        {
            if (tctlDoc.Tabs.Count > 0)
            {
                this.tctlDoc.AutoCloseTabs = false;
                TabItem item = (TabItem)sender;
                //Point mp = Cursor.Position;
                MouseEventArgs mp = (MouseEventArgs)e;
                Point pTab = item.CloseButtonBounds.Location;
                if (mp.X >= pTab.X && mp.X <= pTab.X + item.CloseButtonBounds.Width && mp.Y >= pTab.Y &&
                    mp.Y <= pTab.Y + item.CloseButtonBounds.Height)
                {

                    if (App.Ask("是否关闭当前病人的文书？"))
                    {                      
                        this.tctlDoc.Tabs.Remove(item);

                    }
                }
            }
        }

        /// <summary>
        /// 设置树图标
        /// </summary>
        /// <param name="nodes">节点集合</param>
        private void SetTreeNodesImage(NodeCollection nodes)
        {
            for (int i = 0; i < nodes.Count; i++)
            {
                if (nodes[i].Parent == null)
                {
                    nodes[i].Image = global::CLIENT_EMR.Properties.Resources.住院记录;
                }
                else if (nodes[i].Nodes.Count > 0 && nodes[i].Parent != null)
                {
                    nodes[i].Image = global::CLIENT_EMR.Properties.Resources.文书类型;
                }
                else
                {
                    if (nodes[i].Tag != null)
                    {
                        Class_Text cunrrentDir = nodes[i].Tag as Class_Text;
                        if (cunrrentDir != null)
                        {
                            if (cunrrentDir.Issimpleinstance == "0")   //是单例文书
                            {
                                nodes[i].Image = global::CLIENT_EMR.Properties.Resources.单例文书;
                            }
                            else
                            {
                                nodes[i].Image = global::CLIENT_EMR.Properties.Resources.多例文书;
                            }
                        }
                    }
                }

                if (nodes[i].Nodes.Count > 0)
                {
                    SetTreeNodesImage(nodes[i].Nodes);
                }
            }
        }

        private void tabControl2_TabIndexChanged(object sender, EventArgs e)
        {
            
        }


        /// <summary>
        /// 文书绑定工具栏按钮的设置
        /// </summary>
        private  void SetToolEvent(frmText cf)
        {
            ComHelp.CurrentFrmText = cf;

            App.A_Commit = null;
            App.A_Commit += new EventHandler(ComHelp.saveDocument);

            App.A_Template = null;
            App.A_Template += new EventHandler(getTemplate);

            App.A_Print = null;
            App.A_Print = new EventHandler(ComHelp.CurrentFrmText.MyDoc.PrintEdit);


            App.A_PrintContinue = null;
            App.A_PrintContinue = new EventHandler(SetEnableJumpPrint);

            //App.A_TemplateSave = null;
            //App.A_TemplateSave += new EventHandler(saveTemplate);

            App.A_TempSave = null;
            App.A_TempSave += new EventHandler(ComHelp.saveDocument);
        }

        /// <summary>
        /// 模版提取
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void getTemplate(object sender, EventArgs e)
        {
            if (KindText == "")
            {
                App.MsgWaring("请先确定要提取模版的文书！");
                return;
            }
            ucDocOperater.SelectTemplate = "";
            frmGetTemplate fc = new frmGetTemplate(KindText);
            fc.ShowDialog();

            if (SelectTemplate != "")
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(SelectTemplate);
                CurrentFrmText.MyDoc.FromXML(xmldoc.DocumentElement);
                CurrentFrmText.MyDoc.ContentChanged();
            }            
        }

        /// <summary>
        /// 续打参数设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SetEnableJumpPrint(object sender, EventArgs e)
        {
            if (ComHelp.CurrentFrmText.MyDoc.EnableJumpPrint)
                ComHelp.CurrentFrmText.MyDoc.EnableJumpPrint = false;
            else
                ComHelp.CurrentFrmText.MyDoc.EnableJumpPrint = true;
        }

        private void tabControl2_SelectedTabChanged(object sender, TabStripTabChangedEventArgs e)
        {
            KindText = ""; //清空文书类型
            if (tctlDoc.SelectedTabIndex != -1)
            {
                if (tctlDoc.SelectedPanel.Controls.Count > 0)
                {
                    CurrentFrmText = null;
                    frmText tempEditor = tctlDoc.SelectedPanel.Controls[0] as frmText;                    
                    if (tempEditor != null)
                    {
                        CurrentFrmText = tempEditor;
                        KindText=tempEditor.MyDoc.Us.TextKind_id.ToString();
                        SetToolEvent(tempEditor);
                    }
                }
            }
            else
            {
 
            }
        }

        /// <summary>
        /// 当前选中的节点，是否再tctlDoc.Tabs集合里面已经存在，存在true,否则false
        /// </summary>
        /// <param name="tid">文书的id</param>
        /// <returns></returns>
        private bool IsSameTabItem(string tid, string cTime)
        {
            bool flag = false;
            for (int i = 0; i < tctlDoc.Tabs.Count; i++)
            {
                InPatientInfo inpatient = tctlDoc.Tabs[i].Tag as InPatientInfo;
                if (inpatient != null)
                {
                    if (inpatient.Sick_Bed_Id == inpatient.Sick_Bed_Id)
                    {
                        string tabtid = "";
                        if (tctlDoc.Tabs[i].Name.Split(';').Length >= 4 && !tctlDoc.Tabs[i].Name.Contains("Class_Text"))
                        {
                            tabtid = tctlDoc.Tabs[i].Name.Split(';')[2];
                        }
                        else
                        {
                            tabtid = tctlDoc.Tabs[i].Name.Split(';')[0];
                        }
                        if (tabtid.Equals(tid))
                        {
                            if (tctlDoc.Tabs[i].Name.Split(';').Length <= 4
                                || (tctlDoc.Tabs[i].Name.Split(';').Length > 4 && tctlDoc.Tabs[i].Name.Split(';')[4] == cTime))
                            {
                                flag = true;
                                tctlDoc.SelectedTab = tctlDoc.Tabs[i];
                                App.Msg("已经存在相同的文书！");
                                break;
                            }
                        }
                    }
                }
            }
            return flag;
        }

        ///// <summary>
        ///// 判断该类单例文书是否已经存在
        ///// </summary>
        ///// <param name="id"></param>
        ///// /// <param name="patient_id">病人id</param>
        ///// <returns></returns>
        //private string isExitRecord(int id, int patient_id)
        //{
        //    string sql = "select tid num from t_patients_doc where textkind_id =" + id + " and patient_id='" + patient_id + "' ";
        //    //union select tid from t_care_doc  where textkind_id =" + id + " and inpatient_id='" + patient_id + "'
        //    string tid = App.wc.ReadSqlVal(sql, 0,false, "num");
        //    return tid;
        //}

        /// <summary>
        /// 删除树节点，如果tablContrain容器中也有对应的文书，则删除
        /// </summary>
        private void ClearTabtl()
        {
            int count = tctlDoc.Tabs.Count;
            for (int i = 0; i < count; i++)
            {
                if ((trvAllText.SelectedNode.Parent != null && 
                    tctlDoc.Tabs[i].Name.Contains(trvAllText.SelectedNode.Parent.Name)) ||
                    tctlDoc.Tabs[i].Name.Contains(trvAllText.SelectedNode.Name))
                {
                    tctlDoc.Tabs[i].Dispose();
                    tctlDoc.Controls[i].Dispose();
                    break;
                }
            }
        }


        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (trvFinishDoc.SelectedNode != null)
                {
                    if (trvFinishDoc.SelectedNode.Tag != null)
                    {
                        if (App.Ask("确定需要删除“" + trvFinishDoc.SelectedNode.Text + "”?"))
                        {
                            string DocType = trvFinishDoc.SelectedNode.Tag.ToString();
                            wcfresalut=App.wc.DeleteDocById(trvFinishDoc.SelectedNode.Name, DocType, ComHelp.patientinfo, App.UserAccount.UserInfo.User_id, App.UserAccount.UserInfo.User_name);
                            if (wcfresalut == 0)
                            {
                                ClearTabtl();
                                if (trvFinishDoc.SelectedNode.Parent.Nodes.Count == 1)
                                {
                                    trvFinishDoc.SelectedNode.Parent.Remove();
                                }
                                else
                                {
                                    trvFinishDoc.SelectedNode.Remove();
                                }
                            }
                            else
                            {
                                App.Msg("只能有病人的管床医生或上级医生，有权删除文书。");
                            }
                        }
                    }
                }
                else
                {
                    App.MsgWaring("请选择需要删除的文书！");
                }

            }
            catch(Exception ex)
            {
                App.MsgErr("删除失败,原因："+ex.Message);
            }
        }

        /// <summary>
        /// 已写文书的修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void trvFinishDoc_DoubleClick(object sender, EventArgs e)
        {
            //验证TabControl是否有重复           
                for (int i = 0; i < tctlDoc.Tabs.Count; i++)
                {
                    if (trvFinishDoc.SelectedNode.Text == tctlDoc.Tabs[i].Text)
                    {
                        tctlDoc.SelectedTabIndex = i;
                        return;
                    }
                }
                if (trvFinishDoc.SelectedNode.Nodes.Count == 0)
                {
                    int tid = Convert.ToInt32(trvFinishDoc.SelectedNode.Name);
                    CreateTabItem(tid);
                  
                }
        }
       


        #region 相关事件
        /// <summary>
        /// 浏览文书
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 浏览ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string result = null;
            string tid = "";
            string account_Type = App.UserAccount.CurrentSelectRole.Role_type;
            if (trvFinishDoc.SelectedNode != null)
            {

                if (IsSameTabItem(trvFinishDoc.SelectedNode.Name, DateTime.Now.ToString("yyyy-MM-dd HH:mm")))
                    return;

                DevComponents.DotNetBar.TabControlPanel tabctpnDoc = new DevComponents.DotNetBar.TabControlPanel();
                tabctpnDoc.AutoScroll = true;
                DevComponents.DotNetBar.TabItem pageDoc = new DevComponents.DotNetBar.TabItem();



                pageDoc.Name = trvFinishDoc.SelectedNode.Name;
                pageDoc.Text = trvFinishDoc.SelectedNode.Text + " 浏览";

                
                pageDoc.Click += new EventHandler(page_Click);


                InPatientInfo tempInpatinet = null;

                tempInpatinet = ComHelp.patientinfo;
                pageDoc.Tag = tempInpatinet as object;
                InPatientInfo inpat = pageDoc.Tag as InPatientInfo;
                string textTitle = GetTextTitle(trvFinishDoc.SelectedNode);
                frmText ucText = new frmText(Convert.ToInt32(trvFinishDoc.SelectedNode.Name), 0, 0, textTitle, tempInpatinet.Id, inpat, true);              
                ucText.MyDoc.OnDrawPageHeader += ComHelp.EMRDoc_OnDrawPageHeader;
                ucText.MyDoc.OwnerControl.ContextMenuStrip.Items[3].Visible = false;//LIS
                ucText.MyDoc.OwnerControl.ContextMenuStrip.Items[4].Visible = false;//pacs             
                XmlDocument tempxmldoc = new XmlDocument();
                tempxmldoc.PreserveWhitespace = true;
                tempxmldoc.LoadXml("<emrtextdoc/>");
                ucText.MyDoc.ToXML(tempxmldoc.DocumentElement);
                ucText.MyDoc.Locked = true;
                ucText.MyDoc.EnableShowAll = true;

                string NewXML = "";

                if (trvFinishDoc.SelectedNode.Tag.GetType().ToString().Contains("Class_Text"))
                {

                    NewXML = App.wc.GetXmlDocs(trvFinishDoc.SelectedNode.Name, ComHelp.patientinfo.Id.ToString(), "Class_Text", tempxmldoc.OuterXml);
                }
                else if (trvFinishDoc.SelectedNode.Tag.GetType().ToString().Contains("Patient_Doc"))
                {
                    NewXML = App.wc.GetXmlDocs(trvFinishDoc.SelectedNode.Name, ComHelp.patientinfo.Id.ToString(), "Patient_Doc", tempxmldoc.OuterXml);
                }

                tempxmldoc = new XmlDocument();
                tempxmldoc.LoadXml(NewXML);
                ucText.MyDoc.FromXML(tempxmldoc.DocumentElement);
                tabctpnDoc.Controls.Add(ucText);
                App.UsControlStyle(ucText);
                tabctpnDoc.TabItem = pageDoc;
                tabctpnDoc.Dock = DockStyle.Fill;
                ucText.Dock = DockStyle.Fill;
                pageDoc.AttachedControl = tabctpnDoc;
                this.tctlDoc.Controls.Add(tabctpnDoc);
                this.tctlDoc.Tabs.Add(pageDoc);
                this.tctlDoc.Refresh();
                this.tctlDoc.SelectedTab = pageDoc;                             
                ucText.MyDoc.Locked = true;
                ucText.MyDoc.EnableShowAll = true;
            }
        }

        private void btnTemplate_Click(object sender, EventArgs e)
        {
            try
            {
                if (App.A_Template != null)
                {
                    App.A_Template(sender, e);
                }
                else
                {
                    App.MsgWaring("请先确定文书类型！");
                }
            }
            catch
            {
                App.MsgWaring("请先确定文书类型！");
                App.A_Template = null;
            }
        }

        private void btnTempSave_Click(object sender, EventArgs e)
        {
            
            try
            {
                if (App.A_TempSave != null)
                {
                    App.A_TempSave(sender, e);
                    RefFinishText();
                }
                else
                {
                    App.MsgWaring("该按钮参数未设置或功能尚未启用！");
                }
            }
            catch
            {
                App.MsgWaring("该按钮参数未设置或功能尚未启用！");
                App.A_TempSave = null;
            }
        }

        private void btnCommit_Click(object sender, EventArgs e)
        {
            try
            {
                if (App.A_Commit != null)
                {
                    App.A_Commit(sender, e);
                    RefFinishText();
                }
                else
                {
                    App.MsgWaring("该按钮参数未设置或功能尚未启用！");
                }
            }
            catch
            {
                App.MsgWaring("该按钮参数未设置或功能尚未启用！");
                App.A_Commit = null;
            }
        }

        private void btnContinuePrint_Click(object sender, EventArgs e)
        {
            try
            {
                if (App.A_PrintContinue != null)
                {
                    App.A_PrintContinue(sender, e);
                }
                else
                {
                    App.MsgWaring("该按钮参数未设置或功能尚未启用！");
                }
            }
            catch
            {
                App.MsgWaring("该按钮参数未设置或功能尚未启用！");
                App.A_PrintContinue = null;
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                if (App.A_Print != null)
                {
                    App.A_Print(sender, e);
                }
                else
                {
                    App.MsgWaring("该按钮参数未设置或功能尚未启用！");
                }
            }
            catch
            {
                App.MsgWaring("该按钮参数未设置或功能尚未启用！");
                App.A_Print = null;
            }
        }
        #endregion

       

    }
}
